<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鼠标拖拽效果</title>
    <style>
        #box {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: blue;
            background-image: url(../20221214/img_4.webp);
            background-size: 100%;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        let box = document.getElementById("box")
        // 鼠标在元素上按下开始拖拽
        box.onmousedown = function () {
            // 获取按下鼠标时 盒子与页面的距离
            let originBoxX = box.offsetLeft;
            let originBoxY = box.offsetTop;
            // 获取按下鼠标时 盒子与页面的距离
            let mouseX = event.pageX;
            let mouseY = event.pageY;
            // 在页面上移动
            window.onmousemove = function () {
                // 鼠标滑动的距离 = 鼠标移动后的位置 - 按下鼠标时的位置
                let distanceX = event.pageX - mouseX
                let distanceY = event.pageY - mouseY
                // 规定移动范围
                let left = originBoxX + distanceX
                let top = originBoxY + distanceY
                if(left < 0){
                    left = 0
                // innerWidth 可视窗口的宽度
                }else if(left > innerWidth - 100){
                    left = innerWidth - 100
                }
                if(top < 0){
                    top = 0
                }else if(top > innerHeight - 100){
                    top = innerHeight - 100 
                }
                // 给元素重新赋值 上左定位的位置
                box.style.left = left + "px"
                box.style.top = top + "px"
            }
            // 鼠标松开取消事件
            window.onmouseup = function(){
                // 解绑在页面上滚动的事件
                window.onmousemove = null
            }
        }


    </script>
</body>

</html>